package com.example.tianling.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.tianling.common.exception.TianLingException;
import com.example.tianling.dao.RoomUserMapper;
import com.example.tianling.dao.UserMapper;
import com.example.tianling.entity.RoomEntity;
import com.example.tianling.entity.RoomUserEntity;
import com.example.tianling.entity.UserEntity;
import com.example.tianling.service.RoomService;
import com.example.tianling.service.RoomUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class RoomUserServiceImpl
        extends ServiceImpl<RoomUserMapper, RoomUserEntity>
        implements RoomUserService {

    @Autowired
    private RoomService roomService;

    @Override
    public List<RoomUserEntity> getRoomUserList(Integer roomId) {
        List<RoomUserEntity> roomUserList = this.lambdaQuery()
                .eq(RoomUserEntity::getRoomId, roomId)
                .list();
        return roomUserList;
    }
    @Override
    public void insertRoomUser(RoomUserEntity roomUser) {
        baseMapper.insert(roomUser);
    }
    @Override
    public void updateUserState(String userId, int userState) {
        this.lambdaUpdate()
                .set(RoomUserEntity::getUserState, userState)
                .eq(RoomUserEntity::getUserId, userId)
                .update();
    }


    @Override
    public void removeUserByUserId(Integer userId) {
        QueryWrapper<RoomUserEntity> roomUserWrapper = new QueryWrapper<>();
        roomUserWrapper.eq("user_id", userId);
        this.remove(roomUserWrapper);
    }


    /*
     * 加入房间 service层
     * 1.根据roomId查询房间，房间不存在则抛出异常(code=404, msg="房间不存在")
     * 2.检查人数是否已满，人数已满则抛出异常(code="402", msg="房间人数已满")
     * 3.人未满，插入到room_user表中
     * 4.更新room表中的real_number
     */
    @Override
    public void insertRoomUser(Integer roomId, UserEntity user) {
        RoomUserEntity roomUser = new RoomUserEntity();
        roomUser.setUserId(user.getUserId());
        roomUser.setUserName(user.getUserName());
        roomUser.setUserImg(user.getUserImg());
        roomUser.setUserState(-1);
        roomUser.setRoomId(roomId);

        baseMapper.insert(roomUser);
    }


    @Override
    public void removeUserByRoomId(Integer roomId) {
        QueryWrapper<RoomUserEntity> roomUserWrapper = new QueryWrapper<>();
        roomUserWrapper.eq("room_id", roomId);
        this.remove(roomUserWrapper);
    }

    @Override
    public RoomUserEntity checkRoomUser(Integer roomId, Integer userId) {
        RoomUserEntity roomUser = this.lambdaQuery()
                .eq(RoomUserEntity::getRoomId, roomId)
                .eq(RoomUserEntity::getUserId, userId)
                .last("LIMIT 1")
                .one();
        return roomUser;
    }
}
